###########################################################################
# $Id: SQLManagerInstances.p 13 2009-04-17 10:30:44Z donbeave $
###########################################################################

@CLASS
SQLManagerInstances

@USE
pf/web/pfSiteModule.p

@BASE
pfSiteModule

@OPTIONS
locals

#----- Constructor -----

@create[hshOptions]
## hshOptions.manager
## hshOptions.managerOptions
  ^BASE:create[$hshOptions]

  ^if(def $hshOptions.manager && $hshOptions.manager is dbManager){
    $self._manager[$hshOptions.sql]
  }{
     $self._manager[]
   }

  $self._responseType[json]

#  $self._templatePath[]

  ^addRewritePattern[database/:schema<\w+>;tables]
  ^addRewritePattern[database/:schema<\w+>/:table<\w+>;tablefields]

#----- Events -----

@postJSON[hshResponse]
  ^assignVar[body;$hshResponse.body]

  ^if($hshResponse.body is hash){
    ^assignVar[action;$hshResponse.body.action]
    ^assignVar[data;$hshResponse.body.data]

    ^switch[$hshResponse.body.action.name]{
      ^case[getSchemas]{
        ^assignVar[schemasList;$hshResponse.body.data]

        ^render[db.schemas.^_responseType.upper[].pt]
      }
      ^case[getTables]{
        ^assignVar[tablesList;$hshResponse.body.data]

        ^render[db.tables.^_responseType.upper[].pt]
      }
      ^case[getFields]{
        ^assignVar[fieldsList;$hshResponse.body.data]

        ^render[db.fields.^_responseType.upper[].pt]
      }
    }
  }

@onDatabase[objAction]
  ^redirectTo[schemas]

@onSchemas[objAction]
  $oSchemas[^MANAGER.getSchemas[]]

  $result[
    $.body[
      $.action[
        $.name[getSchemas]
        $.type[get]
        $.status(0)
      ]
      $.data[$oSchemas]
    ]
  ]

@onTables[objAction]
  $oTables[^MANAGER.getTables[$objAction.schema]]

  $result[
    $.body[
      $.action[
        $.name[getTables]
        $.type[get]
        $.status(0)
        $.params[
          $.schema[$objAction.schema]
        ]
      ]
      $.data[$oTables]
    ]
  ]

@onTablefields[objAction]
  $oFields[^MANAGER.getTableFields[$objAction.table;$objAction.schema]]

  $result[
    $.body[
      $.action[
        $.name[getFields]
        $.type[get]
        $.status(0)
        $.params[
          $.schema[$objAction.schema]
          $.table[$objAction.table]
        ]
      ]
      $.data[$oFields]
    ]
  ]

#----- Properties -----

@GET_MANAGER[]
  ^if(!def $self._manager){
    $self._manager[^managerFactory[^if(def $_createOptions.sqlConnectString){$_createOptions.sqlConnectString}{$MAIN:SQL.connect-string};$_createOptions.managerOptions]]
  }
  $result[$_manager]

#----- Fabriques -----

@managerFactory[strConnectString;hshOptions]
  ^switch[^strConnectString.left(^strConnectString.pos[://])]{
    ^case[mysql]{
      ^use[db/dbManagerMySQL.p]
      $result[^dbManagerMySQL::create[
        $.sqlConnectString[$strConnectString]
      ]]
    }
    ^case[DEFAULT]{
      ^pfAssert:fail[SQLManagerInstances.managerFactory. Bad connect-string.]
    }
  }